<template>
	<view class="yz pullflexbox" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend">
		<!-- 头像信息部分 (弹性盒子)-->
		<view class="yz relative" :style="{ height: heights + 'rpx', transition: transitions + 's' }">
			<image class="bg-flter wid1p" :src="UserInfo.avatar ? UserInfo.avatar : 'http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg'"
			 mode="scaleToFill" :style="{ transform: 'scale(' + scales + ')' }"></image>
			<view class="horizontal-center flex flex-col ali-cen wid1p" style="height: inherit; background: rgba(0,0,0,0.2);">
				<!-- 头像框 -->
				<view class="hdImg-w  flex ali-cen just-cent mt80">
					<image class="hdImg-n" :src="UserInfo.avatar ? UserInfo.avatar : 'http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg'"
					 mode="aspectFill"></image>
				</view>
				<!-- 名字 -->
				<view class="fo-white mt40">{{ UserInfo.Nickname || '洋盘小主：' }}</view>
				<view class="fo-white mt20">{{ articleTotal }}条发布</view>
			</view>
		</view>



		<!-- 发布内容部分    Card-->
		<template v-if="data_list.length>0">
			<!-- #ifdef H5 -->
			<transition-group name="list" tag="view">
				<!-- #endif -->
				<view class="Card flex flex-col ali-cen padd20 mt20" v-for="i in data_list" :key="i._id">
					<view class="card-hd wid1p flex just-spa-bet ali-cen">
						<!-- 头部 -->
						<view class="hd-info flex just-spa-bet ali-cen">
							<image :src="i.UserInfo[0].avatar ? i.UserInfo[0].avatar : 'http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg'"
							 class="yicon-lg radius50p mr20" mode="scaleToFill"></image>
							<view class="info">
								<view class="">{{ i.UserInfo[0].Nickname }}</view>
								<text class="fo-gray fo-24">{{ $tool.friendlyDate(new Date(i.PublishTime)) }}</text>
							</view>
						</view>
						<view></view>
						<view v-if='!opt.UserId' class="hd-optera rotate-90 self-start"><text class="cuIcon-more fo-40" @click="onMore(i._id)"></text></view>
					</view>

					<!-- 文字部分 -->
					<text class="card-content wid1p mt20 pl94 pr50 maxHeight" :class="{lookAll:i.isLookAll}" selectable="true" style="line-height: 24px;">
						{{ i.contents }}
					</text>
					<view class="relative wid1p pl94 mt20">
						<text class="fo-blue" style="margin-bottom: -50rpx;" v-if="i.contents.length>50 &&i.isLookAll===false" @click="onLookAll(i._id)">展开全文</text>
					</view>


					<!-- 图片部分  视频图片不可同事存在-->
					<view class="card-imgList wid1p" v-if="i.PushType === 'img/text'">
						<imgList class="mt20" :imgJsonList.sync="i.imgList"></imgList>
					</view>

					<!-- 视频部分 -->
					<view class="card-imgList wid1p" v-if="i.PushType === 'video/text'" @click="$pub.naviTo('/pages/community/videoPlayer')">
						<videoCover class="mt20" :VideoInfo.sync="i.videoList[0].tempFileURL"></videoCover>
					</view>

					<!-- 录音部分 -->
					<view class="self-start pl94 mt40 flex ali-cen fo-white" v-if="i.PushType === 'audio/text'" @click="onAudio(i)">
						<view class="RecordAudio radius20 flex just-spa-bet ali-cen" style="background-color: skyblue; width: 400rpx;height: 80rpx;">
							<view class="ml30">
								<view v-if="!i.isPlayAudio_ing"><text class="cuIcon-playfill"></text></view>
								<view v-else><text class="cuIcon-stop"></text></view>
							</view>
							<text class="font-wei600 mr30">{{i.audioList.duration}}S</text>
						</view>

					</view>

					<!-- 底部评论点赞部分 -->
					<view class="card-foot flex just-spa-bet mt20 paddtb40 pl20">
						<text class="cuIcon-share fo-40" @click="$pub.Toast('功能开发中~')"></text>
						<view class="flex ali-cen">
							<view class="flex ali-cen paddlr20">
								<like-toggle size="16" @change="onLike" :iSlike="i.iSlike" :_id='i._id'></like-toggle>
								<text v-if="i.likeList">{{ i.likeCount }}</text>
							</view>
							<view class="flex ali-cen paddlr20" @click="onCommon(i._id)">
								<text class="cuIcon-community fo-40 mr10"></text>
								<text v-if="i.CommonList">{{ i.CommonList.length }}</text>
							</view>
						</view>
					</view>
				</view>
				<!-- #ifdef H5 -->
			</transition-group>
			<!-- #endif -->
		</template>




		<!-- 暂无内容 -->
		<view class="no-data" v-else>
			<image src="../../../../static/img/community/no_data.png" style="width: 240rpx;height: 280rpx;"></image>
			<text>该用户暂无发布动态</text>
		</view>


		<!-- 点击更多弹窗 -->
		<DropDown :isShow_H5_Mask.sync="isShow_H5_Mask" position="bottom" :isMask="true">
			<view slot="content" class="bottom-list">
				<view class="bottom-list-item" @click="">
					<text class="cuIcon-message bg-DarkTurquoise"></text>
					<text class="mt20">置顶</text>
				</view>
				<view class="bottom-list-item">
					<text class="cuIcon-friendadd bg-Orange"></text>
					<text class="mt20">权限</text>
				</view>
				<view class="bottom-list-item" @click="onDelte">
					<text class="cuIcon-warn bg-OrangeRed"></text>
					<text class="mt20">删贴</text>
				</view>
				<view class="bottom-list-item" @click="isShow_H5_Mask = false">
					<text class="cuIcon-close bg-Snow"></text>
					<text class="mt20">取消</text>
				</view>
			</view>
		</DropDown>
		<!-- 拟态框弹窗 -->
		<YModal :YModalShow.sync='YModalShow' title='提示' :content='YModalTxt' @SubmitOk='YModal_SubmitOk'></YModal>
	</view>
</template>

<script>
	let StartScrollY, MoveScrollY, timer;

	import {
		mapGetters
	} from 'vuex';
	import YModal from '@/common/components/Y-showModel/index.vue'
	import imgList from '../../../community/conpoment/imgList.vue';
	import videoCover from '@/pages/community/conpoment/videoCover.vue';
	import likeToggle from '@/common/components/like-toggle/index.vue';
	import DropDown from '@/pages/public/DropDownPopup.vue';
	import {
		API$SelPersionPublish
	} from '../../../../common/API/home.js';
	import {
		API$like,
		API$DelArticle
	} from '../../../../common/API/community.js';
	export default {
		props: {
			opt: {
				type: Object,
				default () {
					return {};
				}
			},
			SelJson:{
				type: Object,
				default () {
					return {};
				}
			}
		},
		name: '',
		components: {
			imgList,
			videoCover,
			likeToggle,
			DropDown,
			YModal
		},
		data() {
			return {
				UserInfo: [], // 发布者信息
				data_list: [], // 发布者所有文章
				// 下拉弹性盒子
				CurrentTopPositon: 0,
				heights: 580,
				transitions: 0,
				scales: 1,

				isShow_H5_Mask: false, // DropDownPopup是否显示(文件操作栏)
				DelAricleID: null ,// 用来指定删除文章的id
				
				articleTotal:0 ,// 文章总数
				
				
				YModalShow: false, //拟态框
				YModalTxt: '是否删除该动态？', // 拟态框提示内容
			};
		},
		watch: {
			isShow_H5_Mask() {
				this.isShow_H5_Mask ? '' : this.DelAricleID = null
			}
		},
		computed: {
			...mapGetters(['GET_innerAudioContext', 'GET_AudioFileID'])
		},
		async created() {
			console.warn(this.opt)
			this.SelArticle()

		},
		methods: {
			// 拟态框确认回调
			YModal_SubmitOk() {
				console.log(this.DelAricleID)
				this.DelArticle({
					articleId: this.DelAricleID
				})
			},
			onMore(e) {
				this.DelAricleID = e
				this.isShow_H5_Mask = true
			},
			// 点赞
			async onLike(CurrenState, e) {
				if (CurrenState === '请不要频繁点赞') return
				let {
					code,
					msg,
					iSlike
				} = await API$like({
					_id: e, // 这个id是该文章的id
					UserId: this.$pub.getStorageSync('UserInfo')._id // 这个id是用户的id
				});
				if (code === 200 && iSlike) {
					this.data_list.forEach(i => {
						if (i._id === e) {
							this.$set(i, 'iSlike', true);
							this.$set(i, 'likeCount', i.likeCount + 1)
						}
					});
				} else if (code === 200 && !iSlike) {
					this.data_list.forEach(i => {
						if (i._id === e) {
							this.$set(i, 'iSlike', false);
							this.$set(i, 'likeCount', i.likeCount - 1)
						}
					})

				}
				this.$pub.Toast(msg);
			},
			// 评论
			onCommon(e) {
				this.$pub.naviTo(`/pages/community/common?ArticleId=${e}`);
			},
			// 加载/播放/暂停音频
			onAudio(item) {
				/*
					因为我的录音播放管理器是全局的 每次切换录音都是 重新赋值Src 然后控制实例的播放和暂停
						那么我每个播放条（前端页面）都是一个组件  里面的isPlayAudio_ing是分开的，我在切换实例的时候同时我要控制每次组件的isPlayAudio_ing变化，以及倒计时
							所以我还要记录上一次点击播放的状态的isPlayAudio_ing 和状态倒计时
							
							我已经换成在主接口的数据添加isPlayAudio_ing字段 然后每次点击刷新回原来的字段了
				*/
				item.isPlayAudio_ing = !item.isPlayAudio_ing // 改变状态
				let oftenFn = () => {
					this.FreshArticleList({
						CallType: 'reset',
						_id: item._id
					})
					this.$store.commit('CHANGE_innerAudioContext', uni.createInnerAudioContext())
					this.$store.commit('SetAudioSrc', item.audioList.fileUrl)
					this.GET_innerAudioContext.onTimeUpdate(res => { // 监听播放进度
						let durationS = Math.floor(item.audioList.primaryDuration - this.GET_innerAudioContext.currentTime)
						item.audioList.duration = durationS <= 0 ? 0 : durationS
					});
					this.GET_innerAudioContext.onEnded(res => {
						console.log('监听音频自然播放完成事件', this.GET_innerAudioContext);
						item.isPlayAudio_ing = false;
						item.audioList.duration = item.audioList.primaryDuration
					});
				}


				if (this.GET_AudioFileID === item.audioList.fileID) {
					console.log('已经点击过一次播放，再点击就是同一个实例了', this.GET_innerAudioContext)

				} else if (this.GET_AudioFileID === 'fitstLoad') {
					console.log('第一次加载')
					oftenFn()
				} else {
					console.log('第一次加载后再点击其他的音频（离开了当前的实例')
					this.$store.commit('DestroyAudio')
					oftenFn()
				}


				item.isPlayAudio_ing ? this.$store.commit('PlayAudio') : this.$store.commit('PauseAudio')
				this.$store.commit('CHANGE_fileID', item.audioList.fileID)
			},

			// 删除文章
			onDelte() {
				this.YModalShow = true
			},
			// 更新数据状态
			FreshArticleList(res) {
				let {
					CallType,
					state,
					ArticleId,
					data,
					_id
				} = res;

				// 重新刷新数组的某个值
				if (CallType === 'reset') {
					this.data_list.forEach((i, j) => {
						this.$set(i, 'isPlayAudio_ing', false)
						if (i._id === _id) {
							this.$set(i, 'isPlayAudio_ing', true)
						}
					})
				}
			},

			/**********************************************数据接口封装***************************************************/
			// 查询文章
			async SelArticle(type) {
				type==='分页'?this.$emit('Send',this.SelJson.pageNum+1):""
				if(this.SelJson.pageNum * this.SelJson.pageSize > this.articleTotal){
					return
				}
					
				let SelJson = Object.assign({
					UserId: this.$pub.getStorageSync('UserInfo')._id,
					PersionId: this.opt.UserId ? this.opt.UserId : this.$pub.getStorageSync('UserInfo')._id // 如果是主页点击我的发布就执行后部分 如果是社区头像点进来就执行前部分
				},JSON.parse(JSON.stringify(this.SelJson)))
				let {
					code,
					msg,
					data,
					total
				} = await API$SelPersionPublish(SelJson);
				if (code === 200) {
					this.$pub.Toast(msg);
					this.UserInfo = data.UserInfo
					for (let i = 0; i < data.ArticleList.length; i++) {
						data.ArticleList[i]['isLookAll'] = false
						data.ArticleList[i]['isPlayAudio_ing'] = false
						data.ArticleList[i].PushType === 'audio/text' ? data.ArticleList[i]['audioList']['primaryDuration'] = data.ArticleList[
							i].audioList.duration : "" // 原时长/  用来重新赋值
					}
					this.data_list = this.data_list.concat(JSON.parse(JSON.stringify(data.ArticleList)));
					this.articleTotal = total

					this.opt.UserId ? uni.setNavigationBarTitle({
						title: this.UserInfo.Nickname + '的空间'
					}) : ""
				}
			},
			// 删除文章
			async DelArticle(Json) {
				let {
					code,
					msg,
					data
				} = await API$DelArticle(Json)
				if (code === 200) {
					this.$pub.Toast(msg)
					this.isShow_H5_Mask = false
					
					// this.SelArticle()
					for(let i=0;i<this.data_list.length;i++){
						if(this.data_list[i]._id===Json.articleId){
							console.log(this.data_list[i]._id)
							this.data_list.splice(i,1)
						}
					}
				}
			},
			// 展开全文
			onLookAll(e) {
				this.data_list.forEach((i, j) => {
					if (i._id === e) {
						this.$set(i, 'isLookAll', true)
					}
				})
			},
			/*下拉弹性盒子封装************************************************************************************************/
			panduan() {
				let views = uni.createSelectorQuery().select('.pullflexbox');
				views
					.boundingClientRect(data => {
						this.CurrentTopPositon = data.top;
					})
					.exec();
			},
			touchstart(e) {
				StartScrollY = e.touches[0].clientY;
				this.transitions = 0;
			},
			touchmove(e) {
				this.panduan(MoveScrollY);

				if (MoveScrollY > e.touches[0].clientY - StartScrollY) {
					// console.log('上滑');
					// console.log(StartScrollY - e.touches[0].clientY)
					MoveScrollY = e.touches[0].clientY - StartScrollY;
					if (this.heights <= 580 || this.scales <= 1) {
						return;
					}
					this.heights = this.heights - MoveScrollY * 0.005;

					this.scales = 1 + MoveScrollY * 0.001;

				} else {
					// 下滑
					MoveScrollY = e.touches[0].clientY - StartScrollY;
					// console.log('下滑');
					if (this.heights > 600) {
						this.heights = this.heights + MoveScrollY * 0.005;
						this.scales = this.scales + MoveScrollY * 0.001 * 0.01;
						return;
					}
					this.heights = this.heights + MoveScrollY * 0.009;
					this.scales = 1 + MoveScrollY * 0.001;
				}
			},
			touchend(e) {
				this.heights = 580;
				this.transitions = 0.5;
				this.scales = 1;
				StartScrollY = null;
				MoveScrollY = null;
			}
		}
	};
</script>
<style scoped lang="less">
	.yz {
		// height: 480rpx;
		overflow: hidden;
	}

	.bg-flter {
		position: absolute;
		top: 0;
		height: inherit;
		background: url('https://img.tukuppt.com/bg_grid/00/09/84/sVm4mICsz6.jpg!/fh/350');
		background-color: rgba(0, 0, 0, 0.3);
		-webkit-filter: blur(2px);
		-moz-filter: blur(2px);
		-ms-filter: blur(2px);
		-o-filter: blur(2px);
		filter: blur(2px);
		z-index: 0;
	}

	.hdImg-w {
		height: 190rpx;
		width: 190rpx;
		background-color: #ffffff;
		border-radius: 50%;
		z-index: 3;
	}

	.hdImg-n {
		height: 180rpx;
		width: 180rpx;
		border-radius: 50%;
		z-index: 3;
	}
</style>
<style lang="less" scoped>
	.Card {
		width: 100%;
	}

	.card-content {
		// text-indent: 2em;
	}

	.card-foot {
		align-self: flex-end;
		width: 89%;
	}




	// 操作栏弹窗列
	.bottom-list {
		display: flex;
		background-color: #fff;
		box-sizing: border-box;

		// height: 200rpx;
		.bottom-list-item {
			flex: 1;
			padding: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			color: #000;

			text[class^='cuIcon-'] {
				border-radius: 50%;
				height: 100rpx;
				width: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 40rpx;
				color: #000;
			}
		}
	}


	// 展开全部
	.maxHeight {
		max-height: 200rpx;
		overflow: hidden;
	}

	.lookAll {
		max-height: none;
	}


	// 暂无图片
	.no-data {
		display: flex;
		flex-direction: column;
		width: 100%;
		align-items: center;
		margin-top: 160rpx;
		color: gray;
		font-size: 32rpx;
	}


	// 过渡动画
	.Card {
		transition: all 1s;
	}

	.list-enter,
		{
		opacity: 0;
		transform: translateY(100px);
	}

	.list-leave-to {
		opacity: 0;
		transform: translateY(10px);
	}

	.list-leave-active {
		position: absolute;
	}
</style>
